package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.atguigu.tingshu.album.mapper.AlbumInfoMapper;
import com.atguigu.tingshu.album.mapper.TrackInfoMapper;
import com.atguigu.tingshu.album.mapper.TrackStatMapper;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.album.TrackStat;
import com.atguigu.tingshu.query.album.TrackInfoQuery;
import com.atguigu.tingshu.user.client.UserFeignClient;
import com.atguigu.tingshu.vo.album.AlbumTrackListVo;
import com.atguigu.tingshu.vo.album.TrackInfoVo;
import com.atguigu.tingshu.vo.album.TrackListVo;
import com.atguigu.tingshu.vo.album.TrackMediaInfoVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class TrackInfoServiceImpl extends ServiceImpl<TrackInfoMapper, TrackInfo> implements TrackInfoService {

    @Autowired
    private TrackInfoMapper trackInfoMapper;
    @Qualifier("com.atguigu.tingshu.user.client.UserFeignClient")
    @Autowired
    private UserFeignClient userFeignClient;

    @Override
    public IPage<AlbumTrackListVo> findAlbumTrackPage(IPage<AlbumTrackListVo> trackPage, Long albumId) {
        //查出了分页数据，要设置isShowPaidMark标志才可以返回，默认都是免费。
        IPage<AlbumTrackListVo> albumTrackListVo = trackInfoMapper.selectAlbumTrackPage(trackPage, albumId);

        //看专辑信息的付费类型
        AlbumInfo albumInfo = albumInfoMapper.selectById(albumId);
        String payType = albumInfo.getPayType();


        //从token中获取用户id，判断是否登录
        Long userId = AuthContextHolder.getUserId();
        //未登录或token失效（就是未登录）
        //已登录，还要加入是否是vip的逻辑。
        boolean isLogin =  userId == null ? false : true;

        //如果用户未登录
        if (!isLogin) {
            if (payType.equals(SystemConstant.ALBUM_PAY_TYPE_VIPFREE)
                    || payType.equals(SystemConstant.ALBUM_PAY_TYPE_REQUIRE)) {
                //自动放行免费集数，其他的声音要做判断拦截
                int freeTrackCount = albumInfo.getTracksForFree();
                albumTrackListVo.getRecords().stream().filter(
                        albumTrackListVo1 -> albumTrackListVo1.getOrderNum() > freeTrackCount
                ).forEach(
                        //这里都是等待确认的声音,需要根据map来查找，未登录其实根据不用找了，就没什么了，后面，好像也不需要查表
                        albumTrackListVo1 ->
                                albumTrackListVo1.setIsShowPaidMark(true)
                );
            }
        }

        UserInfoVo userInfoVo = userFeignClient.getUserInfoVo(userId).getData();


        //如果用户登录
        if (isLogin) {
            //先判断用户是否为vip
            boolean isVipNow = (userInfoVo.getIsVip().intValue() == 1
                    && userInfoVo.getVipExpireTime().after(new Date()))
                    ? true : false;

               if((payType.equals(SystemConstant.ALBUM_PAY_TYPE_VIPFREE) || payType.equals(SystemConstant.ALBUM_PAY_TYPE_FREE))
                       &&  !isVipNow ) {
                   albumTrackListVo.getRecords().stream().filter(
                           albumTrackListVo1 -> albumTrackListVo1.getOrderNum() > 0
                   ).forEach(
                           //这里都是等待确认的声音,需要根据map来查找,看买了什么专辑，从而设置其他的付费标志显现
                           albumTrackListVo1 ->
                                   albumTrackListVo1.setIsShowPaidMark(true)
                   );
               }

               //如果是vip的话，并且专辑是vip免费，那就直接保持默认值即可,即什么都不操作

              //如果专辑付费的话，那就是不是vip都不管用，直接查表即可
              if(payType.equals(SystemConstant.ALBUM_PAY_TYPE_REQUIRE)) {
                  albumTrackListVo.getRecords().stream().filter(
                          albumTrackListVo1 -> albumTrackListVo1.getOrderNum() > 0
                  ).forEach(
                          //这里都是等待确认的声音,需要根据map来查找,看买了什么专辑，从而设置其他的付费标志显现
                          albumTrackListVo1 ->
                                  albumTrackListVo1.setIsShowPaidMark(true)
                  );
              }

        }


        return albumTrackListVo;
    }

    @Autowired
    private AlbumInfoMapper albumInfoMapper;

    @Autowired
    private VodService vodService;

    /**
     * 保存声音
     * @param trackInfoVo
     *
     *  album_info 包含声音总数同步
     *  track_info 业务主表
     *  track_stat  初始化声音统计数据
     *
     *
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveTrackInfo(TrackInfoVo trackInfoVo) {

        //查询专辑信息
        AlbumInfo albumInfo = albumInfoMapper.selectById(trackInfoVo.getAlbumId());
        //获取包含声音总数
        Integer includeTrackCount = albumInfo.getIncludeTrackCount();
        //转换声音数据
        TrackInfo trackInfo = BeanUtil.copyProperties(trackInfoVo, TrackInfo.class);
        //补充需要的数据
        Long userId = AuthContextHolder.getUserId();
        trackInfo.setUserId(userId);
        //添加排序字段
        trackInfo.setOrderNum(includeTrackCount + 1);
        //根据声音ID获取媒体信息
        TrackMediaInfoVo trackMediaInfoVo = vodService.getMediaInfoByMediaFielId(trackInfoVo.getMediaFileId());

        if (trackMediaInfoVo != null) {

            trackInfo.setMediaType(trackMediaInfoVo.getType());
            trackInfo.setMediaDuration(new BigDecimal(trackMediaInfoVo.getDuration()));
            trackInfo.setMediaSize(trackMediaInfoVo.getSize());
        }


        trackInfo.setSource(SystemConstant.TRACK_SOURCE_USER);
        trackInfo.setStatus(SystemConstant.TRACK_STATUS_PASS);
        //1.保存声音信息
        trackInfoMapper.insert(trackInfo);
        Long trackId = trackInfo.getId();

        //2.初始化声音统计
        this.initTrackStat(trackId, SystemConstant.TRACK_STAT_PLAY);
        this.initTrackStat(trackId, SystemConstant.TRACK_STAT_COLLECT);
        this.initTrackStat(trackId, SystemConstant.TRACK_STAT_PRAISE);
        this.initTrackStat(trackId, SystemConstant.TRACK_STAT_COMMENT);


        //3.同步专辑包含声音总数
        albumInfo.setIncludeTrackCount(includeTrackCount + 1);
        albumInfo.setUpdateTime(new Date());
        albumInfoMapper.updateById(albumInfo);

    }

    /**
     *  获取当前用户声音分页列表
     * @param trackListVoPage
     * @param query
     * @return
     * album_info
     * track_info
     * track_stat
     *
     */
    @Override
    public Page<TrackListVo> findUserTrackPage(Page<TrackListVo> trackListVoPage, TrackInfoQuery query) {


        return trackInfoMapper.selectUserTrackPage(trackListVoPage, query);
    }

    /**
     * 修改保存声音
     * @param id
     * @param trackInfoVo
     */
    @Override
    public void updateTrackInfo(Long id, TrackInfoVo trackInfoVo) {
        //根据ID查询声音信息
        TrackInfo trackInfo = trackInfoMapper.selectById(id);
        //获取之前id
        String beforeMediaFileId = trackInfo.getMediaFileId();
        //获取之后id
        String afterMediaFileId = trackInfoVo.getMediaFileId();
        //拷贝一下
        BeanUtils.copyProperties(trackInfoVo, trackInfo);
        trackInfo.setUpdateTime(new Date());


        //判断
        if (!beforeMediaFileId.equals(afterMediaFileId)) {
            //调用vod删除云点播存储声音
            TrackMediaInfoVo trackMediaInfoVo = vodService.getMediaInfoByMediaFielId(trackInfoVo.getMediaFileId());

            trackInfo.setMediaSize(trackMediaInfoVo.getSize());
            trackInfo.setMediaType(trackMediaInfoVo.getType());
            trackInfo.setMediaDuration(new BigDecimal(trackMediaInfoVo.getDuration()));

            //删除原来的声音
//			vodService.deleteMediaInfoByMediaFielId(trackInfo.getMediaFileId());
            vodService.deleteMediaInfoByMediaFielId(beforeMediaFileId);

        }


        //修改声音
        trackInfoMapper.updateById(trackInfo);
    }

    /**
     * 删除声音信息
     * @param id
     *
     * track_info 删除信息
     * track_stat 删除信息
     * album_info 更新包含总数
     * 云点播  删除声音
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeTrackInfo(Long id) {

        //查询声音信息
        TrackInfo trackInfo = trackInfoMapper.selectById(id);
        //获取专辑ID
        Long albumId = trackInfo.getAlbumId();
        //1.删除声音信息
        trackInfoMapper.deleteById(id);
        //2.删除统计信息
        trackStatMapper.delete(new QueryWrapper<TrackStat>().eq("track_id", id));
        //3.更新包含总数
        AlbumInfo albumInfo = albumInfoMapper.selectById(albumId);
        //设置包含总数
        albumInfo.setIncludeTrackCount(albumInfo.getIncludeTrackCount() - 1);
        albumInfo.setUpdateTime(new Date());
        albumInfoMapper.updateById(albumInfo);

        //更新声音顺序
        //  update track_info  set order_num=order_num-1 where order_num>5 and  album_id=1 and is_deleted=0
        trackInfoMapper.updateOrderNum(trackInfo.getOrderNum(), albumId);


        //4.删除云点播存储声音
        vodService.deleteMediaInfoByMediaFielId(trackInfo.getMediaFileId());

    }


    @Autowired
    private TrackStatMapper trackStatMapper;

    /**
     * 声音初始化
     * @param trackId
     * @param statType
     */
    public void initTrackStat(Long trackId, String statType) {
        TrackStat trackStat = new TrackStat();
        trackStat.setTrackId(trackId);
        trackStat.setStatType(statType);
        trackStat.setStatNum(0);

        trackStatMapper.insert(trackStat);

    }
}
